package cn.xxx.org.controller;

import cn.xxx.basic.exception.BusinessException;
import cn.xxx.basic.util.AjaxResult;
import cn.xxx.basic.util.PageList;
import cn.xxx.org.domain.Shop;
import cn.xxx.org.query.ShopQuery;
import cn.xxx.org.service.IShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 写接口
 *      我们需要烤炉以下三点
 *      1.请求路径是什么
 *      2.请求参数是什么
 *      3.返回值是什么
 */
@RestController//返回前端json数据
@RequestMapping("/shop")
@Api(tags = "门店接口",description = "门店接口详细描述")
public class ShopController {
    @Autowired
    IShopService shopService;

    //新增和修改
    @ApiOperation(value = "门店添加或修改",notes = "如果有id就是修改否则就是添加")
    @PutMapping //@RequestBody 从请求体中拿数据
    public AjaxResult addOrUpdate(@RequestBody Shop shop){
        try {
            if(shop.getId()==null){
                shopService.add(shop);
            }else {
                shopService.update(shop);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess("操作失败！");
        }
    }

    //查询一条数据
    @ApiOperation(value = "查询一条数据",notes = "根据id查询")
    @GetMapping("/{id}")
    public Shop getById(@PathVariable("id") Long id){
        return shopService.getById(id);
    }

    //删除
    @ApiOperation(value = "删除一条数据",notes = "根据id删除")
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            shopService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess("操作失败！");
        }
    }

    //分页
    @ApiOperation(value = "分页",notes = "查询每页数据")
    @PostMapping
    public PageList<Shop> queryPage(@RequestBody ShopQuery shopQuery){
        return shopService.queryPage(shopQuery);
    }

    @ApiOperation(value = "批量删除",notes = "")
    @PatchMapping  //如果前端传递的是数组，那么后端使用list或者array接收
    public AjaxResult patchDelete(@RequestBody List<Long> ids){
        try {
            shopService.patchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess("操作失败！");
        }
    }

    @GetMapping
    public List<Shop> getAll(){
        return shopService.getAll();
    }

    @PostMapping("/settlement")
    public AjaxResult settledIn(@RequestBody Shop shop){
        try {
            shopService.settledIn(shop);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess("系统繁忙，稍后重试"+e.getMessage());
        }
    }
}
